package com.ifonly.activerecord;

import com.ifonly.utils.ReflectUtils;

import java.io.Serializable;
import java.util.Map;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-17 16:03
 * @since JDK 1.6
 */
public class Record implements Access, Serializable {
    private static final long serialVersionUID = 1867428307838375265L;

    private Map<String, Object> columnAndValues;

    public Map<String, Object> getColumnAndValues() {
        return columnAndValues;
    }

    public void setColumnAndValues(Map<String, Object> columnAndValues) {
        this.columnAndValues = columnAndValues;
        this.accessor = new Accessor(this.columnAndValues);
    }

    public Model toModel(Class<? extends Model> clazz) {
        Model model = ReflectUtils.newInstance(clazz);
        model.setAll(columnAndValues);
        return model;
    }

    // ----------------------------------------------------------------------------- gets
    private Accessor accessor;

    public Accessor getAccessor() {
        synchronized (this) {
            if (accessor == null) {
                accessor = new Accessor(this.columnAndValues);
            }
        }
        return accessor;
    }

    @Override
    public Object get(String property) {
        return getAccessor().get(property);
    }

    @Override
    public Number getNumber(String property) {
        return getAccessor().getNumber(property);
    }

    @Override
    public String getString(String property) {
        return getAccessor().getString(property);
    }

    @Override
    public String getString(String property, String defaultValue) {
        return getAccessor().getString(property, defaultValue);
    }

    @Override
    public Long getLong(String property) {
        return getAccessor().getLong(property);
    }

    @Override
    public long getLongValue(String property) {
        return getAccessor().getLongValue(property);
    }

    @Override
    public long getLongValue(String property, long defaultValue) {
        return getAccessor().getLongValue(property, defaultValue);
    }

    @Override
    public int getInt(String property) {
        return getAccessor().getInt(property);
    }

    @Override
    public int getInt(String property, int defaultValue) {
        return getAccessor().getInt(property, defaultValue);
    }

    @Override
    public Integer getInteger(String property) {
        return getAccessor().getInteger(property);
    }

}
